package com.haifeng.wdsh.gateway.filter;

import com.haifeng.wdsh.common.base.constants.Constants;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

/**
 * <p>
 *  Swagger过滤器
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-05-05
 */
@Order(4)
@Component
public class SwaggerHeaderFilter extends AbstractGatewayFilterFactory {

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getPath();
            if (!StringUtils.endsWithIgnoreCase(path, Constants.SWAGGERPV2 )) {
                return chain.filter(exchange);
            }
            String basePath = path.substring(0, path.lastIndexOf(Constants.SWAGGERPV2));
            ServerHttpRequest newRequest = request.mutate().header(Constants.HEADER_NAME, basePath).build();
            ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
            return chain.filter(newExchange);
        };
    }
}
